#!/usr/bin/env bash
#################################################################################
#作者：zangxw
#当前版本:v1.0
#Linux系统工具脚本
#################################################################################

LINUX_TOOLS_DIR="/opt/linuxTools"                                                             #安装目录
DOWNLOAD_URL="https://gitee.com/zangxw/linuxTools/releases/download/latest/linuxTools.tar.gz" #脚本文件下载地址
DOWNLOAD_URL_FILE="https://download.06171230.xyz" #文件下载地址

# 判断所属系统运行对应命令安装
function install_soft() {
  if command -v dnf >/dev/null; then
    dnf -q -y install "$1"
  elif command -v yum >/dev/null; then
    yum -q -y install "$1"
  elif command -v apt >/dev/null; then
    apt-get -qqy install "$1"
  elif command -v zypper >/dev/null; then
    zypper -q -n install "$1"
  elif command -v apk >/dev/null; then
    apk add -q "$1"
    command -v gettext >/dev/null || {
      apk add -q gettext-dev python3
    }
  else
    echo -e "[\033[31m ERROR \033[0m] $1 command not found, Please install it first"
    exit 1
  fi
}
# 安装基础命令
function prepare_install() {
  echo -e "[\033[31m 检查安装所需命令 - Command required for installation \033[0m]"
  for i in curl wget tar; do
    command -v $i &>/dev/null || install_soft $i
  done
}

# 下载脚本
function download() {
  echo -e "\033[1;31m 下载相关sh脚本至${LINUX_TOOLS_DIR} - download install script to ${LINUX_TOOLS_DIR} \033[0m"

  cd /opt || exit 1

  timeout 10 wget -qO linuxTools.tar.gz ${DOWNLOAD_URL} || {
    rm -f /opt/linuxTools.tar.gz
    echo -e "[\033[31m ERROR \033[0m] 下载失败 - Failed to download"
    echo -e "[\033[31m ERROR \033[0m] 请手动下载: ${DOWNLOAD_URL} "
    exit 1
  }

  tar -xf /opt/linuxTools.tar.gz -C /opt/linuxTools || {
    rm -rf /opt/linuxTools
    echo -e "[\033[31m ERROR \033[0m] 解压失败 - Failed to unzip"
    exit 1
  }
  rm -f /opt/linuxTools.tar.gz
}

# 安装基础命令
prepare_install

mkdir /opt/linuxTools &>/dev/null

# 判断是否需要下载脚本
if [ ! -e "./scripts/docker/docker.sh" ]; then
  if [ ! -e "${LINUX_TOOLS_DIR}/scripts/docker/docker.sh" ]; then
    download
  fi

  cd ${LINUX_TOOLS_DIR} || exit 1

  chmod 777 main.sh
  ./main.sh
else
  chmod 777 main.sh
  ./main.sh
fi
